import { customRef } from "vue";

/**
 * 防抖
 * @param {Function} func  回调函数
 * @param {number} delay 间隔时间
 */
export const debounce = function (func: Function, delay: number = 500) {
  let timer: any = null;
  return function (this: any, ...args: any) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;
    }, delay);
  };
};
/**
 * 封装防抖的vue ref
 * @param value 值
 * @param delay 时间
 * @returns
 */
export const debounceRef = (value: any, delay: number = 1000) => {
  let timer: any = null;
  const func = debounce((val: any, trigger: any) => {
    value = val;
    trigger();
  }, delay);
  return customRef((track: any, trigger: any) => {
    return {
      get() {
        track(); // 收集依赖
        return value;
      },
      set(val) {
        func(val, trigger);
      },
    };
  });
};

/*
使用方法
<script setup lang="ts">
import {debounceRef} from '@/utils/function'
const searchValue=debounceRef('')
</script>
<template>
 <input v-model="searchValue" />

</template>



*/

/**
 * 节流
 * @param {Function} func  回调函数
 * @param {number} delay 间隔时间
 */
export const throttle = function (func: Function, delay: number = 1000) {
  let timer: any = null;
  return function (this: any, ...args: any) {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      func.apply(this, args);
      timer = null;
    }, delay);

  };
};

export function hidePhone(tel:string){
  if(!tel) return ''
  var reg = /^(\d{3})\d{4}(\d{4})$/;  
  return tel.replace(reg, "$1****$2");
}